package com.softstao.guoyu.ui.activity.sale;

import android.Manifest;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.GsonManager;
import com.softstao.guoyu.global.UserManager;
import com.softstao.guoyu.model.sale.OrderDetail;
import com.softstao.guoyu.model.sale.OrderGoods;
import com.softstao.guoyu.model.sale.PayCondition;
import com.softstao.guoyu.model.sale.ToOrder;
import com.softstao.guoyu.mvp.interactor.UploadInteractor;
import com.softstao.guoyu.mvp.presenter.UploadPresenter;
import com.softstao.guoyu.mvp.viewer.UploadTargetViewer;
import com.softstao.guoyu.ui.adapter.OrderGoodsAdapter;
import com.softstao.guoyu.ui.baseAdapter.CommonBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.ViewHolder;
import com.softstao.softstaolibrary.library.activity.ImagePagerActivity;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomGridView;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.LZToast;
import com.softstao.softstaolibrary.library.widget.progressBar.RoundProgressBarWidthNumber;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/21.
 */

public class OrderPayActivity extends BaseActivity implements UploadTargetViewer{

    @AIPresenter(presenter = UploadPresenter.class,interactor = UploadInteractor.class)
    UploadPresenter presenter;

    @BindView(R.id.order_sn)
    TextView orderSn;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.orderer)
    TextView orderer;
    @BindView(R.id.status)
    TextView status;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.total_price)
    TextView totalPrice;
    @BindView(R.id.balance_pay)
    TextView balancePay;
    @BindView(R.id.line_pay)
    TextView linePay;
    @BindView(R.id.memo)
    EditText memo;
    @BindView(R.id.pic_view)
    CustomGridView picView;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.progress_layout)
    RelativeLayout progressLayout;
    @BindView(R.id.progress)
    RoundProgressBarWidthNumber progress;
    private int type = 6;
    private String state,order_code,order_date,name,total;
    private List<OrderGoods> goodsList = new ArrayList<>();
    private OrderDetail orderDetail;
    private ToOrder toOrder;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private OrderGoodsAdapter adapter;
    public final static int PAY_IMAGE = 100;
    private PayCondition condition = new PayCondition();
    private CommonBaseAdapter<String> imgAdapter;
    private List<String> datas = new ArrayList<>();

    @Override
    public int _ContentView() {
        return R.layout.activity_order_pay;
    }

    @Override
    public void initView() {
        initTitle("付款");
        state = getIntent().getStringExtra("status");
        balancePay.setSelected(true);
        balancePay.setText("虚拟支付(余额"+ LZUtils.priceFormat(UserManager.getInstance().getUser().getBalance()) + ")");
        switch (state){
            case "detail":
                orderDetail = (OrderDetail) getIntent().getSerializableExtra("order_detail");
                order_code = orderDetail.getOrderCode();
                order_date = format.format(new Date(orderDetail.getOrderDate()));
                name = orderDetail.getConsigneeInfo().getName();
                total = getResources().getString(R.string.rmb) + LZUtils.priceFormat(orderDetail.getTotal());
                goodsList.clear();
                goodsList.addAll(orderDetail.getOrderProductList());
                break;
            case "transfer":
            case "to":
                toOrder = (ToOrder) getIntent().getSerializableExtra("order_detail");
                order_code = String.valueOf(toOrder.getOrderCode());
                order_date = format.format(new Date(toOrder.getOrderDate()));
                name = toOrder.getToAgentName();
                total = getResources().getString(R.string.rmb) + LZUtils.priceFormat(toOrder.getTotal());
                goodsList.clear();
                goodsList.addAll(toOrder.getOrderProductList());
                break;
        }
        orderSn.setText("订单编号：" + order_code);
        time.setText("时间：" + order_date);
        orderer.setText("订货人：" + name);
        totalPrice.setText(total);

        adapter = new OrderGoodsAdapter(goodsList);
        listView.setAdapter(adapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));

        imgAdapter = new CommonBaseAdapter<String>(datas, R.layout.layout_img) {
            @Override
            public int getCount() {
                int count;
                count = datas.size() == 0 ? 1 : datas.size() + 1;
                return count;
            }

            @Override
            public String getItem(int position) {
                if (datas.size() != 0 && position < datas.size()) {
                    return mdatas.get(position);
                }
                return null;
            }

            @Override
            public void convert(ViewHolder holder, String s) {
                if (datas.size() != 0 && holder.getmPosition() < datas.size()) {
                    Glide.with(context).load(s).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v -> imageBrower(holder.getmPosition(), (ArrayList<String>) datas));
                    holder.getView(R.id.del).setVisibility(View.VISIBLE);
                    holder.getView(R.id.del).setOnClickListener(v -> {
                        datas.remove(holder.getmPosition());
                        notifyDataSetChanged();
                    });
                } else {
                    Glide.with(context).load(R.mipmap.add_pic).into((ImageView) holder.getView(R.id.img));
                    holder.getView(R.id.img).setOnClickListener(v ->
                            new RxPermissions(OrderPayActivity.this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA)
                                    .subscribe(result-> {
                                        if (result){
                                            PictureSelector.create(OrderPayActivity.this)
                                                    .openGallery(PictureMimeType.ofImage())
                                                    .selectionMode(PictureConfig.SINGLE)
                                                    .previewImage(true)
                                                    .isCamera(true)
                                                    .enableCrop(true)
                                                    .freeStyleCropEnabled(true)
                                                    .forResult(PAY_IMAGE);
                                        }
                                    }));
                    holder.getView(R.id.del).setVisibility(View.GONE);
                }
            }
        };
        picView.setAdapter(imgAdapter);
    }

    protected void imageBrower(int position, ArrayList<String> urls2) {
        Intent intent = new Intent(this, ImagePagerActivity.class);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_URLS, urls2);
        intent.putExtra(ImagePagerActivity.EXTRA_IMAGE_INDEX, position);
        startActivity(intent);
    }

    @OnClick({R.id.balance_pay, R.id.line_pay, R.id.submit_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.balance_pay:
                balancePay.setSelected(true);
                linePay.setSelected(false);
                type = 6;
                break;
            case R.id.line_pay:
                balancePay.setSelected(false);
                linePay.setSelected(true);
                type = 7;
                break;
            case R.id.submit_btn:
                condition.setWay(type);
                condition.setPayRemark(memo.getText().toString());
                condition.setImg( GsonManager.getInstance().getGson().toJson(datas));
                if (!check()){
                    return;
                }
                Intent intent = getIntent();
                intent.putExtra("pay",condition);
                setResult(RESULT_OK,intent);
                finish();
                break;
        }
    }

    private boolean check(){
        if (type==0){
            LZToast.getInstance(context).showToast("请选择付款方式");
            return false;
        }
        if(linePay.isSelected()) {
            if (datas.size() == 0) {
                LZToast.getInstance(context).showToast("至少上传一张截图");
                return false;
            }
        }
        return true;
    }

    @Override
    public void uploadForTarget(String tag, File file) {
        presenter.uploadForTarget(tag,file,progress);
        progress.setVisibility(View.VISIBLE);
        progressLayout.setVisibility(View.VISIBLE);
    }

    @Override
    public void uploadResult(String tag, String url) {
        switch (tag){
            case "img":
                datas.add(url);
                imgAdapter.notifyDataSetChanged();
                break;
        }
        progress.setVisibility(View.GONE);
        progressLayout.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PAY_IMAGE:
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    uploadForTarget("img", new File(selectList.get(0).getCutPath()));
                    break;
            }
        }
    }
}
